<template>
  <view>
    <!-- 拍照 -->
    <view class="content">
      <image class="logo" :src=pic_path @click="get_pic_info"></image>

      <view @click="get_pic_info" v-if="scale == true" class="pic_sure" hover-class="pic_sure_hover">扫一扫</view>
      <view v-else @click="pic_determine" class="pic_sure" hover-class="pic_sure_hover">测一测</view>
    </view>

    <!-- 文本搜索 -->
    <canvas canvas-id="canvas" :style="{width:cWidth+'px',height:cHeight+'px'}"
            style="position: absolute;left:-1000px;top:-1000px;"></canvas>


  </view>


</template>

<script>
const MD5 = require('pages/md5/md5.js') // 引入md5.js文件

export default {
  data() {
    return {
      title: 'Hello',
      src: '',
      pic_path: "/static/saoyisao.png",
      Base64: '',
      anmationShow: false,
      garbage_info: '',
      scale: true,
      cWidth: 0,
      cHeight: 0,
    }
  },
  onLoad() {


  },

  methods: {
    urlencode(str) {
      str = (str + '').toString();
      return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
    },
    get_pic_info: function () {
      var that = this
      // uni.authorize({
      //     scope: 'scope.camera',
      //     success() {
      //         uni.getLocation()
      //     }
      // })

      uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: function (res) {
          that.scale = false
          that.pic_path = res.tempFilePaths[0]
          var path = res.tempFilePaths[0]
          uni.showLoading({
            title: '处理中...',
            mask: true
          });
          that.img_zip(path).then(res => {
            console.log("压缩图片", res)
            uni.getFileSystemManager().readFile({
              filePath: res,
              encoding: "base64",
              success: function (data) {
                console.log("base64转换", data)
                that.Base64 = data.data
              },
              fail: function (res) {
                console.log(res)
              }
            })
          }).catch(err => {
            console.log(err)
          })
          // uni.getFileSystemManager().readFile({
          //   filePath: path,
          //   encoding: "base64",
          //   success: function (data) {
          //     console.log("Base64",data.data)
          //     // that.Base64 = data.data
          //     // 获取base64的大小 M
          //     // var size = data.data.length / 1024 / 1024
          //     // console.log("Base64 size",size,that.Base64)
          //     // await that.img_zip(data.data)
          //     // that.Base64 = await that.img_zip( data.data)
          //     // that.Base64 = "aHR0cHM6Ly9pbWcxNC4zNjBidXlpbWcuY29tL24wL2pmcy90NjQyMS8zMS8xNzk1Nzc5NS8xODAzNTUvYzU0ZjEyZGEvNTkzN2Q2ZGJOYTAxNTI0MjQuanBn"
          //   }
          // })


        }
      });


    },
    img_zip(img) {
      console.log("压缩图片", img)
      let that = this
      return new Promise((resolve, reject) => {
        wx.getImageInfo({
          src: img,
          success: function (res) {
            console.log("getImageInfo", res)
            var ratio = 2;
            var canvasWidth = res.width
            var canvasHeight = res.height
            while (canvasWidth > 100 || canvasHeight > 100) {
              canvasWidth = Math.trunc(res.width / ratio)
              canvasHeight = Math.trunc(res.height / ratio)
              ratio++;
            }
            // that.setData({
            //   cWidth: canvasWidth,
            //   cHeight: canvasHeight
            // })
            that.cWidth = canvasWidth
            that.cHeight = canvasHeight

            var ctx = wx.createCanvasContext('canvas')
            ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
            ctx.draw(false, setTimeout(function () {
              wx.canvasToTempFilePath({
                canvasId: 'canvas',
                destWidth: canvasWidth,
                destHeight: canvasHeight,
                success: function (res) {
                  console.log("压缩成功", res.tempFilePath)
                  uni.hideLoading()
                  uni.showToast({
                    title: "压缩成功",
                    icon: 'success',
                    duration: 1000,
                  })
                  resolve(res.tempFilePath) //最终图片路径
                },
                fail: function (res) {
                  console.log(res.errMsg)
                  reject(res.errMsg)
                }
              })
            }, 1000))
          },
          fail: function (res) {
            console.log(res.errMsg)
            reject(res.errMsg)
          }
        })
      })
    },
    pic_determine: function () {
      const that = this
      // 图像数据或图像url，BASE64编码后进行URLENCODE，要求base64编码和URLENCODE后大小不超过2M，最短边至少15PX，最长边最大4096PX,支持JPG/PNG/BMP格式
      const data = ({
        "img": that.urlencode(that.Base64)
      })
      uni.request({
        url: `http://recover.market.alicloudapi.com/recover`,
        method: "POST",
        header: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          "Authorization": `APPCODE 952f35566c55409aa3be8f5ba0abd4fc`
        },
        data: data,
        success: function (res) {
          console.log(res)
          that.scale = true
          if (!res.data || res.data.err) {
            uni.showToast({
              title: `识别失败，${res.data.err}`,
              icon: 'none'
            })
          } else {
            that.garbage_info = res.data.data[0].list[0]
            uni.setStorage({
              key: 'garbage_info', // 命名
              data: that.garbage_info //内容
            });
            var pic_path = that.pic_path
            uni.navigateTo({
              url: '../result/result?pic_path=' + pic_path
            });
          }
        },
        fail: function () {
          uni.showToast({
            title: '识别失败，换个角度。。'
          })
        }
      });
      //获取当前时间戳
      // var timestamp = Date.parse(new Date());
      // // console.log("当前时间戳为：" + timestamp);
      // // 使用加密
      // var SecretKey = '0daf3ab76762797eb6729362ad5d19ea'
      // var miyao = MD5.hexMD5(SecretKey + timestamp).toString(); // 使用加密
      // console.log(SecretKey)
      // console.log(miyao)
      // var that = this
      // var url = 'https://aiapi.jd.com/jdai/garbageImageSearch?appkey=a06479cbfd68f27d900a1073dfdc317d&timestamp=' +
      //     timestamp + '&sign=' + miyao;
      // uni.request({
      //   url: url,
      //   method: "POST",
      //   header: {
      //     'Content-Type': 'application/JSON',
      //   },
      //   data: {
      //     cityId: 310000,
      //     imgBase64: that.Base64
      //   },
      //   success: function (res) {
      //     console.log(res)
      //     that.scale = true
      //     if (res.data.result.status != 0) {
      //       uni.showToast({
      //         title: '识别失败，换个角度。。',
      //         icon: 'none'
      //       })
      //     } else {
      //       that.garbage_info = res.data.result.garbage_info[0]
      //       uni.setStorage({
      //         key: 'garbage_info', // 命名
      //         data: that.garbage_info //内容
      //       });
      //       var pic_path = that.pic_path
      //       uni.navigateTo({
      //         url: '../result/result?pic_path=' + pic_path
      //       });
      //     }
      //   },
      //   fail: function () {
      //     uni.showToast({
      //       title: '识别失败，换个角度。。'
      //     })
      //
      //   }
      //
      // });


    },


  },
}
</script>

<style>
/* 扫一扫 */
.pic_sure {
  width: 300upx;
  line-height: 80upx;
  color: white;
  margin-bottom: 20upx;
  border-radius: 50upx;
  text-align: center;

  background-color: #C8B7AD;

  background-color: rgb(252, 126, 67);
  background: bg_red;
}

.pic_sure_hover {
  background: rgb(236, 179, 156);
}

.content {
  margin-top: 200upx;
  border-radius: 50upx;
  width: 100%;
  height: 600upx;
  background-image: url('http://img5.imgtn.bdimg.com/it/u=3801175907,1027721896&fm=26&gp=0.jpg');
  background-size: cover;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 400upx;
  width: 400upx;
  border-radius: 30upx;
  margin-top: 100upx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50upx;
}
</style>
